package com.eralink.unionuhfreader.util;

public class StringUtils {
    public static byte[] hexStrToBytes(String hexStr) {
        if (null == hexStr || hexStr.isEmpty() || (hexStr.length() % 2) != 0) {
            return new byte[0];
        }

        byte[] bytes = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; ++i) {
            bytes[i] = (byte) Integer.parseInt(hexStr.substring(i * 2, i * 2 + 2), 16);
        }

        return bytes;
    }

    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
    public static String bytesToHexString(byte[] data, int offset, int size) {
        StringBuilder sb = new StringBuilder(size * 2);
        for (int i = 0; i < size; ++i) {
            sb.append(hexCode[(data[offset + i] >> 4) & 0xF]);
            sb.append(hexCode[(data[offset + i] & 0xF)]);
        }
        return sb.toString();
    }

    public static boolean isHexString(final String hex) {
        return !hex.isEmpty() && hex.length() % 2 == 0 && hex.matches("[0-9a-fA-F]+");
    }

    public static boolean bytesEqual(byte[] data1, int offset1, int len1, byte[] data2, int offset2, int len2) {
        assert (null != data1);
        assert (null != data2);

        if (len1 != len2) {
            return false;
        }

        for (int i = 0; i < len1; ++i) {
            if (data1[offset1 + i] != data2[offset2 + i]) {
                return  false;
            }
        }

        return true;
    }
}
